
// key-value 模型
public class HashBucket<K,V> {
    private static class Node<K,V> {
        private K key;
        private V value;
        Node<K,V> next;


        public Node(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }


    private Node<K,V>[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小

    public void put(K key, V value) {
        int head = key.hashCode();
        int index = head % array.length;
        Node<K,V> cur = array[index];
        Node<K,V> parent = null;
        while(cur != null){
            if(cur.key.equals(key)){
                cur.value = value;
                return;
            }
            parent = cur;
            cur = cur.next;
        }
        Node<K,V> node = new Node<>(key,value);
        if(cur == null){
            node.next = array[index];
            array[index] = node;
            return;
        }
        parent.next = node;
        cur.next = null;
        size++;
        if(loadFactor() >= LOAD_FACTOR){
            resize();
        }
    }


    private void resize() {
        Node<K,V>[] newArray = (Node<K,V>[])new Node[2*array.length];
        for(int i = 0;i < array.length;i++){
            Node<K, V> cur = array[i];
            while(cur != null){
                int index = cur.key.hashCode() % array.length;
                Node<K, V> curN = cur.next;
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curN;
            }
            array = newArray;
        }
    }


    private double loadFactor() {
        return size * 1.0 / array.length;
    }


    public HashBucket() {
        array = (Node<K,V>[])new Node[10];
    }


    public V get(K key) {
         int hash = key.hashCode();
         int index = hash % array.length;
         Node<K,V> cur = array[index];
         while(cur != null){
             if(cur.key.equals(key)){
                 return cur.value;
             }
             cur = cur.next;
         }
         return null;
    }
}